<template>
  <el-popover
    placement="bottom-end"
    :width="300"
    trigger="manual"
    :visible="visible"
    @update:visible="handleVisibleChange"
  >
    <template #reference>
      <el-badge
          class="condition-badge"
          :is-dot="hasSettingsChange"
      >
        <el-button
            type="default"
            :icon="Setting"
            @click="handleToggle"
        >
          列设置

        </el-button>
      </el-badge>
    </template>
    
    <div class="column-settings">
      <div class="settings-header">
        <span class="title">列设置</span>
        <div class="actions">
          <el-button
            type="text"
            size="small"
            @click="handleReset"
          >
            重置
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleSave"
          >
            保存
          </el-button>
        </div>
      </div>
      
      <el-divider style="margin: 12px 0" />
      
      <div class="settings-content">
        <div class="select-all">
          <el-checkbox
            v-model="selectAll"
            :indeterminate="isIndeterminate"
            @change="handleSelectAll"
          >
            全选
          </el-checkbox>
        </div>
        
        <div class="column-list">
          <draggable
            v-model="localSettings"
            item-key="prop"
            handle=".drag-handle"
            @end="handleDragEnd"
          >
            <template #item="{ element, index }">
              <div class="column-item">
                <div class="drag-handle">
                  <el-icon><Rank /></el-icon>
                </div>
                <el-checkbox
                  v-model="element.visible"
                  @change="handleColumnVisibleChange"
                >
                  {{ element.label }}
                </el-checkbox>
              </div>
            </template>
          </draggable>
        </div>
      </div>
    </div>
  </el-popover>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { Setting, Rank } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import draggable from 'vuedraggable'
import { ElMessage } from 'element-plus'
import type { TableColumn, ColumnSetting } from './types'
import { ColumnSettingsManager } from './index'

interface Props {
  columns: TableColumn[]
}

interface Emits {
  (e: 'settings-change', settings: ColumnSetting[]): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 路由和用户信息
const route = useRoute()
const userStore = useUserStore()

const visible = ref(false)
const localSettings = ref<ColumnSetting[]>([])

// 计算属性
const selectAll = computed({
  get: () => localSettings.value.every(item => item.visible),
  set: (value: boolean) => {
    localSettings.value.forEach(item => {
      item.visible = value
    })
  }
})

const isIndeterminate = computed(() => {
  const visibleCount = localSettings.value.filter(item => item.visible).length
  return visibleCount > 0 && visibleCount < localSettings.value.length
})

// 判断列设置是否有修改
const hasSettingsChange = computed(() => {
  if (localSettings.value.length === 0) return false
  
  // 获取默认设置
  const defaultSettings = props.columns.map((column, index) => ({
    prop: column.prop,
    visible: !column.hidden,
    order: index
  }))
  
  // 检查可见性变更
  const hasVisibilityChange = localSettings.value.some(setting => {
    const defaultSetting = defaultSettings.find(d => d.prop === setting.prop)
    return defaultSetting && setting.visible !== defaultSetting.visible
  })
  
  if (hasVisibilityChange) return true
  
  // 检查顺序变更
  const hasOrderChange = localSettings.value.some((setting, index) => {
    const defaultSetting = defaultSettings.find(d => d.prop === setting.prop)
    return defaultSetting && defaultSetting.order !== setting.order
  })
  return hasOrderChange
})

// 初始化设置
const initSettings = () => {
  // 先尝试从缓存加载
  const userId = userStore.userInfo?.userId || 'anonymous'
  const pagePath = route.path
  const savedSettings = ColumnSettingsManager.loadColumnSettings(userId, pagePath)
  
  if (savedSettings.length > 0) {
    // 合并保存的设置和当前列配置
    const settingsMap = new Map(savedSettings.map(s => [s.prop, s]))
    localSettings.value = props.columns.map((column, index) => {
      const saved = settingsMap.get(column.prop)
      return {
        prop: column.prop,
        label: column.label,
        visible: saved ? saved.visible : !column.hidden,
        order: saved ? saved.order : index
      }
    }).sort((a, b) => a.order - b.order)
  } else {
    // 使用默认设置
    localSettings.value = props.columns.map((column, index) => ({
      prop: column.prop,
      label: column.label,
      visible: !column.hidden,
      order: index
    }))
  }
}

// 方法
const handleToggle = () => {
  visible.value = !visible.value
}

const handleVisibleChange = (val: boolean) => {
  // 只有在点击外部关闭时才更新visible状态
  // 按钮点击通过handleToggle控制
  if (!val) {
    visible.value = val
  } else {
    // 打开时初始化设置
    initSettings()
  }
}

const handleSelectAll = (value: boolean) => {
  localSettings.value.forEach(item => {
    item.visible = value
  })
}

const handleColumnVisibleChange = () => {
  // 触发响应式更新
}

const handleDragEnd = () => {
  // 更新排序
  localSettings.value.forEach((item, index) => {
    item.order = index
  })
}

const handleReset = () => {
  // 重置为默认设置
  localSettings.value = props.columns.map((column, index) => ({
    prop: column.prop,
    label: column.label,
    visible: !column.hidden,
    order: index
  }))
  
  // 清除缓存
  const userId = userStore.userInfo?.userId || 'anonymous'
  const pagePath = route.path
  ColumnSettingsManager.clearColumnSettings(userId, pagePath)
  ElMessage.success('已重置为默认设置')
}

const handleSave = () => {
  // 保存设置到缓存
  const userId = userStore.userInfo?.userId || 'anonymous'
  const pagePath = route.path
  ColumnSettingsManager.saveColumnSettings(localSettings.value, userId, pagePath)
  
  // 触发事件通知父组件
  emit('settings-change', localSettings.value)
  
  // 关闭弹窗
  visible.value = false
  
  ElMessage.success('列设置已保存')
}

// 监听列变化
watch(
  () => props.columns,
  () => {
    initSettings()
  },
  { immediate: true }
)
</script>

<style scoped>
.column-settings {
  padding: 8px 0;
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-weight: 500;
  font-size: 14px;
  color: #303133;
}

.actions {
  display: flex;
  gap: 8px;
}

.settings-content {
  max-height: 300px;
  overflow-y: auto;
}

.select-all {
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.column-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.column-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
  cursor: move;
}

.column-item:hover {
  background-color: #f5f7fa;
}

.drag-handle {
  color: #909399;
  cursor: move;
  display: flex;
  align-items: center;
}

.drag-handle:hover {
  color: #409eff;
}

:deep(.el-checkbox) {
  flex: 1;
}

:deep(.el-checkbox__label) {
  font-size: 13px;
}
</style>